#include <graphics.h>

#include <array>
#include <vector>
#include <string>

#include "button.h"



const int windowWidth = 800, windowHeight = 600;

// 全局鼠标消息
mouse_msg gMouseMsg = {};
// 全局键盘消息
key_msg gKeyMsg = {};

void load (void);
void eventUpdate (void);
void dataUpdate (void);
void drawInterface (void);

enum {
	MAIN, S1, S2, S3, END
} flag = MAIN; // 初始界面为 MAIN


struct RES {
	PIMAGE res;
	std::string resName;
};
std::vector <RES> res = {
	{nullptr, "./res/main.png"},      // 主界面
	{nullptr, "./res/s1.png"},        // S1
	{nullptr, "./res/s2.png"},        // S2
	{nullptr, "./res/s3.png"},        // S3
	{nullptr, "./res/end.png"}        // 结束
};
std::array <BUTTON, 5> myButtons;
// 0 1 3 界面
// 3 4 退出 返回

int main (int argc, char *argv[]) {

	setinitmode (INIT_RENDERMANUAL);
	initgraph (windowWidth, windowHeight);
	setbkmode (TRANSPARENT);

	load ();

	for (; is_run (); delay_fps (60), cleardevice ()) {

		eventUpdate ();
		dataUpdate ();
		drawInterface ();
	}

	closegraph ();
	return 0;
}

void load (void) {
	// 正常加载代码
	flag = MAIN;
	currentPage = newimage (windowWidth, windowHeight);
	for (auto &a : res) {
		a.res = newimage ();
		getimage (a.res, a.resName.c_str ());
	}

	ege::PIMAGE R = ege::newimage (), P = ege::newimage (), H = ege::newimage (), C = ege::newimage ();
	ege::getimage (R, "./res/RELEASED.jpg");
	ege::getimage (P, "./res/PRESSED.jpg");
	ege::getimage (H, "./res/HOVER.jpg");
	ege::getimage (C, "./res/CLICK.png");
	for (auto &btn : myButtons) {
		btn.setImage (H, R, P, C);
	}
	myButtons [0].setPos (300, 100); // 三个
	myButtons [0].setP2H ([] (int id) { flag = S1; });     // 弹起时
	myButtons [1].setPos (300, 300);
	myButtons [1].setP2H ([] (int id) { flag = S2; });     // 弹起时
	myButtons [2].setPos (300, 500);
	myButtons [2].setP2H ([] (int id) { flag = S3; });     // 弹起时
	myButtons [3].setPos (100, 500); // 退出
	myButtons [3].setP2H ([] (int id) { flag = END; });     // 弹起时
	myButtons [4].setPos (500, 500); // 返回
	myButtons [4].setP2H ([] (int id) { flag = MAIN; });     // 弹起时

	delimage (R);
	delimage (P);
	delimage (H);
	delimage (C);
}

void eventUpdate (void) {
	// 更新事件，主要就是处理键盘事件和鼠标事件
	while (mousemsg ()) {
		gMouseMsg = getmouse ();
	}
	while (kbmsg ()) {
		gKeyMsg = getkey ();
	}
}

void dataUpdate (void) {
	// 更新数据
}

void drawInterface (void) {
	// 最后画出界面

	switch (flag) {
		case MAIN: {
			putimage (0, 0, res [0].res);
			myButtons [0].Show (gMouseMsg);
			myButtons [1].Show (gMouseMsg);
			myButtons [2].Show (gMouseMsg);
		} break;
		case S1: {
			putimage (0, 0, res [1].res);
			myButtons [3].Show (gMouseMsg);
			myButtons [4].Show (gMouseMsg);
		} break;
		case S2: {
			putimage (0, 0, res [2].res);
			myButtons [3].Show (gMouseMsg);
			myButtons [4].Show (gMouseMsg);
		} break;
		case S3: {
			putimage (0, 0, res [3].res);
			myButtons [3].Show (gMouseMsg);
			myButtons [4].Show (gMouseMsg);
		} break;
		case END: {
			putimage (0, 0, res [4].res);
		} break;
		default: {
			// just error
		} break;
	}

}